package _30_io._netty_base;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author liuhuan
 */
public class NettyServer {

    public static void main(String[] args) throws Exception {
        // 创建 boss 线程组，处理 连接请求，个数代表有 几主，每个 主 都需要配置一个单独的监听端口
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        // 创建 worker 线程组，处理 具体业务，个数代表有
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 创建 Server 启动器，配置必要参数：bossGroup, workerGroup, channel, handler
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 对workerGroup的SocketChannel设置处理器
                            socketChannel.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("Netty Server start ...");
            ChannelFuture channelFuture = serverBootstrap.bind(9000).sync();
            // 给 channelFuture 添加监听器，监听是否启动成功
            /*channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("启动成功");
                    } else {
                        System.out.println("启动失败");
                    }
                }
            });*/
            channelFuture.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
